package logic

import (
	"context"
	"fmt"
	"zg1/weipinhui/models/cache"
	"zg1/weipinhui/models/mysql"
	"zg1/weipinhui/pkg"
	"zg1/weipinhui/wphrpc/internal/svc"
	"zg1/weipinhui/wphrpc/wphrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *wphrpc.UpdateRequest) (*wphrpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line

	user := mysql.User{}
	mysql.DB.Where("id=?", in.Id).Find(&user)

	if pkg.Md5(in.Password) != user.Password {
		return nil, fmt.Errorf("密码错误！")
	}

	sms, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Tel).Result()
	if sms != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}

	user.Password = in.NewPassword

	mysql.DB.Updates(&user)

	cache.Rdb.Del(l.ctx, "sendSms"+in.Tel)

	return &wphrpc.UpdateResponse{
		Id: int64(user.ID),
	}, nil
}
